<template>
  <div class="hover-zoom-container" 
       @mouseenter="handleMouseEnter" 
       @mouseleave="handleMouseLeave"
       @mousemove="handleMouseMove">
    <slot></slot>
    <teleport to="body">
      <transition name="zoom-fade">
        <div v-if="showZoomed" class="zoomed-image-container" :style="containerStyle">
          <img :src="imageSrc" class="zoomed-image" :style="imageStyle" />
        </div>
      </transition>
    </teleport>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue';

const props = defineProps({
  imageSrc: {
    type: String,
    required: true
  },
  zoomFactor: {
    type: Number,
    default: 2
  },
  zoomSize: {
    type: Number,
    default: 250
  },
  delay: {
    type: Number,
    default: 300 // 默认延时1秒
  }
});

const showZoomed = ref(false);
const mousePosition = ref({ x: 0, y: 0 });
const imageLoaded = ref(false);
const hoverTimer = ref(null);

// 计算放大容器的样式
const containerStyle = computed(() => {
  return {
    position: 'fixed',
    left: `${mousePosition.value.x}px`,
    top: `${mousePosition.value.y}px`,
    width: `340px`,
    transform: 'translate(-50%, -50%)',
    zIndex: 10000,
    overflow: 'hidden'
  };
});

// 计算图片的样式，根据鼠标位置调整背景位置
const imageStyle = computed(() => {
  return {
    width: '100%',
    objectFit: 'cover'
  };
});

const handleMouseEnter = (event) => {
  if (imageLoaded.value) {
    clearTimeout(hoverTimer.value);
    updateMousePosition(event);
    
    // 设置延时显示
    hoverTimer.value = setTimeout(() => {
      showZoomed.value = true;
    }, props.delay);
  }
};

const handleMouseLeave = () => {
  // 清除定时器，取消显示
  clearTimeout(hoverTimer.value);
  showZoomed.value = false;
};

const handleMouseMove = (event) => {
    if(showZoomed.value) return
  updateMousePosition(event);
};

const updateMousePosition = (event) => {
  mousePosition.value = {
    x: event.clientX,
    y: event.clientY
  };
};

// 预加载图片
onMounted(() => {
  const img = new Image();
  img.src = props.imageSrc;
  img.onload = () => {
    imageLoaded.value = true;
  };
});

// 组件卸载时清除定时器
onUnmounted(() => {
  clearTimeout(hoverTimer.value);
});
</script>

<style>
.hover-zoom-container {
  position: relative;
  display: inline-block;
}

.zoomed-image-container {
  box-shadow: 0 0 20px rgba(0, 0, 0, 0.3);
  pointer-events: none;
}

.zoomed-image {
  display: block;
}

.zoom-fade-enter-active,
.zoom-fade-leave-active {
  transition: opacity 0.2s ease;
}

.zoom-fade-enter-from,
.zoom-fade-leave-to {
  opacity: 0;
}
</style> 